#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QtCore/QCoreApplication>
#include <QFile>
#include <QPixmap>


//**************************************************************
//
//                    CAM SCANNER - PROJECT
//
// version 1.0 - 25.06.2012 Adriano:
//    : first version
//
//**************************************************************

                // standard picture width, our Nokia can take pictures with over 4000px,
                //  but 1600 should be enough and doesn't occupy too much size
#define CAMERA_IMAGE_WIDTH          1600
                // from the height, only 1/4 is taken. We don't need more for a single line. Maybe 1/4 is too much.
#define CAMERA_IMAGE_HEIGHT_SCALE   4

//*****************************************************************************************************************
// Constructor
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

                    // create camera object and initialize it
    m_camera = new QCamera;

    m_previewCapture = 0;

    m_view = new videoView(ui->widget);

    m_camera->setViewfinder(m_view->getVideoWidget());
    m_camera->setCaptureMode(QCamera::CaptureStillImage);

    m_netConnection = new connection(ui->centralWidget);

    connect(m_netConnection, SIGNAL(connected()), this, SLOT(WiFiConnected()));
}

//*****************************************************************************************************************
// Destructor
MainWindow::~MainWindow()
{
    m_camera->stop();
    delete m_camera;
    delete ui;
}

//*****************************************************************************************************************
// Orientation
void MainWindow::setOrientation(ScreenOrientation orientation)
{
#if defined(Q_OS_SYMBIAN)
    // If the version of Qt on the device is < 4.7.2, that attribute won't work
    if (orientation != ScreenOrientationAuto) {
        const QStringList v = QString::fromAscii(qVersion()).split(QLatin1Char('.'));
        if (v.count() == 3 && (v.at(0).toInt() << 16 | v.at(1).toInt() << 8 | v.at(2).toInt()) < 0x040702) {
            qWarning("Screen orientation locking only supported with Qt 4.7.2 and above");
            return;
        }
    }
#endif // Q_OS_SYMBIAN

    Qt::WidgetAttribute attribute;
    switch (orientation) {
#if QT_VERSION < 0x040702
    // Qt < 4.7.2 does not yet have the Qt::WA_*Orientation attributes
    case ScreenOrientationLockPortrait:
        attribute = static_cast<Qt::WidgetAttribute>(128);
        break;
    case ScreenOrientationLockLandscape:
        attribute = static_cast<Qt::WidgetAttribute>(129);
        break;
    default:
    case ScreenOrientationAuto:
        attribute = static_cast<Qt::WidgetAttribute>(130);
        break;
#else // QT_VERSION < 0x040702
    case ScreenOrientationLockPortrait:
        attribute = Qt::WA_LockPortraitOrientation;
        break;
    case ScreenOrientationLockLandscape:
        attribute = Qt::WA_LockLandscapeOrientation;
        break;
    default:
    case ScreenOrientationAuto:
        attribute = Qt::WA_AutoOrientation;
        break;
#endif // QT_VERSION < 0x040702
    };
    setAttribute(attribute, true);
}


//*****************************************************************************************************************
// Expanded - showMiximized is the right way for this little app, we don't need a fullscreen app.
void MainWindow::showExpanded()
{
    showMaximized();
    /*
#if defined(Q_OS_SYMBIAN) || defined(Q_WS_SIMULATOR)
    showFullScreen();
#elif defined(Q_WS_MAEMO_5)
    showMaximized();
#else
    show();
#endif
    */
}


//*****************************************************************************************************************
// User pressed TAKE PHOTO
void MainWindow::on_pushButton_photo_clicked()
{
                    // only if camera is available
    if(m_previewCapture)
    {
        ui->pushButton_photo->setEnabled(false);
                    // emit signal and save image to temp drive. Wait for camera signal.
        m_previewCapture->capture("d:\\imagehd.jpg");
    }
}


//*****************************************************************************************************************
// User pressed EXIT
void MainWindow::on_pushButton_exit_clicked()
{
    m_camera->stop();
    QApplication::closeAllWindows();
}


//*****************************************************************************************************************
// connection class emitted 'connected' signal, initialize camera components
void MainWindow::WiFiConnected()
{
        // TODO: there is something wrong... The focus is lost after this function is over :(
    m_camera->focus()->zoomTo(1.0, 1.0);
    m_camera->focus()->setFocusMode(QCameraFocus::MacroFocus);
    m_camera->imageProcessing()->setContrast(80);
    m_camera->imageProcessing()->setDenoisingLevel(80);
    m_camera->imageProcessing()->setSaturation(-70);
    m_camera->imageProcessing()->setSharpeningLevel(70);
    m_camera->imageProcessing()->setWhiteBalanceMode(QCameraImageProcessing::WhiteBalanceTungsten);
    m_view->show();

        // if wifi was never connected, create camera objects, else the camera objects is already present
    if(!m_previewCapture)
    {
        m_previewCapture = new QCameraImageCapture(m_camera);

        QImageEncoderSettings imageSettings;
        imageSettings.setCodec("image/jpeg");
        imageSettings.setResolution(1600, 1200);
        imageSettings.setQuality(QtMultimediaKit::VeryHighQuality);

        m_previewCapture->setEncodingSettings(imageSettings);

        connect(m_previewCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(imageCaptured(int,QImage)));
        connect(m_previewCapture, SIGNAL(imageSaved(int,QString)), this, SLOT(imageSaved(int,QString)));

        connect(m_camera, SIGNAL(stateChanged(QCamera::State)), this, SLOT(cameraStateChanged(QCamera::State)));
    }

    if(m_camera->state() != QCamera::ActiveState) m_camera->start();
}


//*****************************************************************************************************************
// Here a preview can be set. I found out that on my N8 imageSaved is emitted before this function.
//   So I don't see why loose time on this function.
void MainWindow::imageCaptured(int id, QImage im)
{

}


//*****************************************************************************************************************
// Camera object made a photo, save it and send it to the server.
void MainWindow::imageSaved(int id, QString im)
{
    QImage im1(im);
    int w = im1.width();
    int h = im1.height();
                    // Why /4 and /2? Well, also with the macro, the image is not focused. So it is better if the camera has
                    //   an higher distance and we take only the half image (like a digital zoom).
                    // This zoom is already present in the video-widget.
    im1 = im1.copy(w/4, h/4, w/2, h/2);
    w = im1.width();
    h = im1.height();
                    // Get only 1/4 of the height.
                    // Scale the entire image to a with o 1200px.
    m_im2 = im1.copy(0,
                   h/2-h/(CAMERA_IMAGE_HEIGHT_SCALE*2),
                   w,
                   h/(CAMERA_IMAGE_HEIGHT_SCALE)).scaledToWidth(1200);
    ui->plainTextEdit->setPlainText("picture resolution: " + QString::number(w) + "x" + QString::number(h) + " - " + QString::number(m_im2.byteCount()/1024) + " kb\n-------------");
    ui->label->setPixmap(QPixmap::fromImage(m_im2));

                    // send the image to the server (this will take some seconds)
    m_netConnection->sendImageOverWiFi(m_im2);

    ui->plainTextEdit->setPlainText(ui->plainTextEdit->toPlainText() + m_netConnection->getMessage());

                    // enable again the button to take a photo
    ui->pushButton_photo->setEnabled(true);
}


//*****************************************************************************************************************
// Camera state changed, TODO: I try to set the focus mode, but it seems that it has no effect
void MainWindow::cameraStateChanged(QCamera::State s)
{
    if(s == QCamera::LoadedState)
    {
        m_camera->focus()->setFocusMode(QCameraFocus::MacroFocus);
        m_camera->searchAndLock();
    }
    else if(s == QCamera::ActiveState)
    {
        m_camera->focus()->setFocusMode(QCameraFocus::MacroFocus);
        m_camera->searchAndLock();
    }
}


//*****************************************************************************************************************
// Manually set focus on the photo. TODO: after taking the first picture, the focus is lost!
void MainWindow::on_pushButton_focus_clicked()
{
    m_camera->focus()->setFocusMode(QCameraFocus::MacroFocus);
    m_camera->searchAndLock();
}
